import React, { useEffect, useMemo, useState } from 'react';
import {
  Table,
  Input,
  Card,
  PaginationProps,
  Modal,
  Form,
  Select,
  Skeleton,
  Message,
} from '@arco-design/web-react';
import { getColumns } from './constants';
import styles from '../../style/index.module.less';
import { Role, User } from '@/api/interface/authentication';
import {
  RoleListByUserId,
  UserList,
  UserSetRole,
} from '@/api/modules/authentication';
import debounce from 'lodash/debounce';
import ModalTitle from '@/components/ModalTitle';

const { Option } = Select;
const { Search } = Input;
const FormItem = Form.Item;

function AuthUsers({ t, rtl }: { t: unknown; rtl: boolean }) {
  const [username, setUserName] = useState('');
  const searchChange = debounce((value) => setUserName(value), 500);

  const [pagination, setPatination] = useState<PaginationProps>({
    sizeOptions: [10, 20, 50, 100],
    sizeCanChange: true,
    showTotal: true,
    pageSize: 10,
    current: 1,
    pageSizeChangeResetCurrent: true,
  });

  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<User[]>([]);
  useEffect(() => {
    getUserList();
  }, [pagination.current, pagination.pageSize, username]);

  const getUserList = async () => {
    const { current, pageSize } = pagination;
    setLoading(true);
    try {
      const { data } = await UserList({
        name: username,
        pageNo: current,
        pageSize,
      });
      setData(data.data);
      setPatination({
        ...pagination,
        current,
        pageSize,
        total: data.count,
      });
    } finally {
      setLoading(false);
    }
  };

  function onChangeTable({ current, pageSize }) {
    setPatination({
      ...pagination,
      current,
      pageSize,
    });
  }

  const [roleList, setRoleList] = useState<Role[]>([]);
  const [roleLoading, setRoleLoading] = useState(false);
  const [activeUser, setActiveUser] = useState<User>({});
  const editRole = async (record) => {
    setVisible(true);
    setActiveUser(record);
    try {
      setRoleLoading(true);
      const { data } = await RoleListByUserId({ userId: record.id });
      setRoleList(data.roles);
      form.setFieldsValue({
        roles: data.roles.filter((item) => item.checked).map((item) => item.id),
      });
    } finally {
      setRoleLoading(false);
    }
  };

  const columns = useMemo(() => getColumns(t, editRole), [t]);

  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);

  const onSubmit = () => {
    form.validate(async (errors, values) => {
      if (errors) return;
      try {
        setConfirmLoading(true);
        await UserSetRole({ userId: activeUser.id, roleId: values.roles });
        Message.success(t['auth.save.success']);
        setVisible(false);
        getUserList();
      } finally {
        setConfirmLoading(false);
      }
    });
  };

  return (
    <Card className={styles['auth-users']}>
      <div className={styles['button-group']}>
        <Search
          allowClear
          placeholder={t['auth.input.placeholder.username']}
          style={{ width: 350 }}
          onChange={searchChange}
        />
      </div>
      <Table
        border={{ wrapper: true, cell: true }}
        rowKey="id"
        loading={loading}
        onChange={onChangeTable}
        pagination={pagination}
        columns={columns}
        data={data}
      />

      {/* edit role modal */}
      <Modal
        title={<ModalTitle title={t['auth.operations.edit.role']} />}
        visible={visible}
        onCancel={() => setVisible(false)}
        onOk={() => onSubmit()}
        confirmLoading={confirmLoading}
        okText={t['auth.operations.save']}
        cancelText={t['auth.operations.cancel']}
      >
        <Skeleton
          image
          text={{ rows: 3, width: ['100%'] }}
          loading={roleLoading}
        >
          <Form
            autoComplete="off"
            form={form}
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 19 }}
          >
            <FormItem label={t['auth.user.form.name'] + ' :'}>
              <div style={{ width: '100%', textAlign: rtl ? 'right' : 'left' }}>
                {activeUser.name}
              </div>
            </FormItem>
            <FormItem
              label={t['auth.user.form.role'] + ' :'}
              field="roles"
              // rules={[
              //   { required: true, message: t['auth.select.placeholder.role'] },
              // ]}
            >
              <Select
                placeholder={t['auth.select.placeholder.role']}
                mode="multiple"
                allowClear
                showSearch
                filterOption={(inputValue, option) =>
                  option.props.children
                    .toLowerCase()
                    .indexOf(inputValue.toLowerCase()) >= 0
                }
              >
                {roleList.map((item) => (
                  <Option key={item.id} value={item.id}>
                    {item.name}
                  </Option>
                ))}
              </Select>
            </FormItem>
          </Form>
        </Skeleton>
      </Modal>
    </Card>
  );
}

export default AuthUsers;
